//
//  PPHomeAlbumSearchView.m
//  pickpic
//
//  Created by Jinxiao on 9/11/16.
//  Copyright © 2016 MicroDream. All rights reserved.
//

#import "PPHomeAlbumSearchView.h"

#import "PPHomeAlbumSearchTableViewCell.h"

#import "PPAlbumModel.h"

#import "Algorithms.h"

@interface PPHomeAlbumSearchView () <UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource>
@property (readwrite, nonatomic, strong) UIView *topBar;
@property (readwrite, nonatomic, strong) UITextField *searchField;
@property (readwrite, nonatomic, strong) UIButton *cancelButton;
@property (readwrite, nonatomic, strong) UITableView *tableView;
@property (readwrite, nonatomic, strong) NSArray <PPAlbumModel *> *albums;
@property (readwrite, nonatomic, strong) UILabel *promptLabel;
@end

@implementation PPHomeAlbumSearchView

- (instancetype)init {
    self = [super init];

    self.backgroundColor = [UIColor whiteColor];

    _topBar = [[UIView alloc] init];
    _topBar.backgroundColor = [UIColor colorWithRGBHex:0xffdd17];
    [self addSubview:_topBar];

    _searchField = [[UITextField alloc] init];
    _searchField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"搜索" attributes:@{NSForegroundColorAttributeName : [UIColor colorWithRGBHex:0xb2b2b2], NSFontAttributeName : [UIFont systemFontOfSize:14]}];
    _searchField.backgroundColor = [UIColor whiteColor];
    _searchField.layer.cornerRadius = 5;
    _searchField.layer.masksToBounds = YES;
    _searchField.font = [UIFont systemFontOfSize:14];
    _searchField.textColor = [UIColor colorWithRGBHex:0x323232];
    _searchField.delegate = self;
    _searchField.autocapitalizationType = UITextAutocapitalizationTypeNone;
    _searchField.autocorrectionType = UITextAutocorrectionTypeNo;
    _searchField.returnKeyType = UIReturnKeyDone;
    _searchField.enablesReturnKeyAutomatically = YES;
    [_topBar addSubview:_searchField];

    UIImageView *iconView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon-search"]];
    iconView.contentMode = UIViewContentModeScaleAspectFit;
    [iconView sizeToFit];
    iconView.width += 20;
    _searchField.leftView = iconView;
    _searchField.leftViewMode = UITextFieldViewModeAlways;

    _cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _cancelButton.contentEdgeInsets = UIEdgeInsetsMake(6, 13, 6, 13);
    _cancelButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [_cancelButton setTitle:@"取消" forState:UIControlStateNormal];
    [_cancelButton setTitleColor:[UIColor colorWithRGBHex:0x323232] forState:UIControlStateNormal];
    [_cancelButton sizeToFit];
    [_topBar addSubview:_cancelButton];

    _promptLabel = [[UILabel alloc] init];
    _promptLabel.text = @"未找到该相册";
    _promptLabel.textColor = [UIColor colorWithRGBHex:0xb2b2b2];
    _promptLabel.font = [UIFont systemFontOfSize:14];
    [_promptLabel sizeToFit];
    _promptLabel.hidden = YES;
    [self addSubview:_promptLabel];

    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    _tableView.dataSource = self;
    _tableView.delegate = self;
    [_tableView registerNib:[UINib nibWithNibName:@"PPHomeAlbumSearchTableViewCell" bundle:nil] forCellReuseIdentifier:@"albumCell"];
    [self addSubview:_tableView];

    UIControl *dismissalControl = [[UIControl alloc] init];
    [dismissalControl addTarget:self action:@selector(dismissalControlDidPressed) forControlEvents:UIControlEventTouchUpInside];
    _tableView.backgroundView = dismissalControl;

    UIView *footerView = [[UIView alloc] init];
    footerView.backgroundColor = [UIColor clearColor];
    footerView.frame = CGRectMake(0, 0, CGFLOAT_MIN, CGFLOAT_MIN);
    _tableView.tableFooterView = footerView;

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldDidChanged) name:UITextFieldTextDidChangeNotification object:nil];

    return self;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidChangeNotification object:nil];
}

- (void)dismissalControlDidPressed {
    [_cancelButton sendActionsForControlEvents:UIControlEventTouchUpInside];
}

- (BOOL)becomeFirstResponder {
    return [_searchField becomeFirstResponder];
}

- (BOOL)resignFirstResponder {
    _searchField.text = nil;

    [self searchKeyword:nil];

    return [_searchField resignFirstResponder];
}

- (void)layoutSubviews {
    [super layoutSubviews];

    _topBar.frame = CGRectMake(0, 0, self.width, 44);

    _cancelButton.right = _topBar.width;
    _cancelButton.centerY = _topBar.height/2;

    _searchField.frame = CGRectMake(10, (_topBar.height - 28)/2, _cancelButton.left - 10, 28);

    _tableView.frame = CGRectMake(0, _topBar.bottom, self.width, self.height - _topBar.bottom);

    _promptLabel.centerX = self.width/2;
    _promptLabel.top = 145;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _albums.count == 0 ? 0 : 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 38;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headerView = [[UIView alloc] init];
    headerView.frame = CGRectMake(0, 0, tableView.width, [self tableView:tableView heightForHeaderInSection:section]);
    headerView.backgroundColor = [UIColor colorWithRGBHex:0xffffff alpha:0.8];

    UILabel *label = [[UILabel alloc] init];
    label.font = [UIFont systemFontOfSize:14];
    label.textColor = [UIColor colorWithRGBHex:0x656565];
    label.text = @"图册";
    [label sizeToFit];
    label.left = 11;
    label.centerY = headerView.height/2;
    [headerView addSubview:label];

    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 76;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _albums.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"albumCell" forIndexPath:indexPath];

    PPAlbumModel *album = [_albums safeObjectAtIndex:indexPath.row];

    ((PPHomeAlbumSearchTableViewCell *)cell).album = album;

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    PPAlbumModel *album = [_albums safeObjectAtIndex:indexPath.row];

    [_delegate searchView:self didSelectAlbum:album];
}

- (void)textFieldDidChanged {
    [self searchKeyword:_searchField.text];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if([string isEqualToString:@"\n"]) {
        [textField resignFirstResponder];

        return NO;
    }

    return YES;
}

- (void)searchKeyword:(NSString *)keyword {

    if(keyword.length == 0) {
        _promptLabel.hidden = YES;
        _albums = nil;
    } else {
        NSArray <PPAlbumModel *> *albums = [PPAlbumModel all];

        const char *pattern = keyword.UTF8String;

        NSMutableArray *filteredAlbums = [NSMutableArray array];
        [albums enumerateObjectsUsingBlock:^(PPAlbumModel *_Nonnull obj, NSUInteger idx, BOOL *_Nonnull stop) {
            if(compare(obj.title.UTF8String, pattern) || compare(obj.title.pinyin.UTF8String, pattern)) {
                [filteredAlbums addObject:obj];
            }
        }];
        _albums = filteredAlbums;

        _promptLabel.hidden = _albums.count > 0;
    }

    [_tableView reloadData];
}

@end
